﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using ClassLibrary.Entity;
using System.Collections.Generic;
using ClassLibrary.Data;
using ClassLibrary.DAO;

public partial class UserControl_ucPayment : System.Web.UI.UserControl
{
    TblEmailDAO emailDAO = new TblEmailDAO(Global.CONNECTION_STRING);
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Session[Global.SESSION_CART] == null || Session[Global.SESSION_LOGGED_USER] == null)
            {
                ScriptManager.RegisterStartupScript(btnPayment, btnPayment.GetType(), "ScriptLoginSuccess", "UpdatePayment();", true);
            }
            else
            {
                lb_email.Text = ((TblCustomers)Session[Global.SESSION_LOGGED_USER]).EmailAdress;
                lb_name.Text = ((TblCustomers)Session[Global.SESSION_LOGGED_USER]).FName + " " + ((TblCustomers)Session[Global.SESSION_LOGGED_USER]).LName;

                lb_OrderDate.Text = DateTime.Now.ToString("dd/MM/yyyy");
                lb_phone.Text = ((TblCustomers)Session[Global.SESSION_LOGGED_USER]).MobilePhone;

                //Load cart
                List<TblBookingDetail> arrItems = new List<TblBookingDetail>();
                if (Session[Global.SESSION_CART] != null)
                    arrItems = (List<TblBookingDetail>)Session[Global.SESSION_CART];

                grdShoppingCart.DataSource = arrItems;
                grdShoppingCart.DataBind();

                lblTotal.Text = (float.Parse(Session[Global.SESSION_TOTAL].ToString())).ToString("c");
            }

        }
    }

    protected void grdShoppingCart_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Cells[0].Text = (e.Row.RowIndex + 1).ToString();
        }
    }
    protected void btnPayment_Click(object sender, EventArgs e)
    {
        bool flag = false;
        if (Session[Global.SESSION_CART] == null || Session[Global.SESSION_LOGGED_USER] == null)
        {
            ScriptManager.RegisterStartupScript(btnPayment, btnPayment.GetType(), "ScriptLoginSuccess", "UpdatePayment();", true);
        }

        // thanh toán tien mat
        if (rd1.Checked == true)
        {
            // insert vao giỏ hàng

            #region insert booking
            try
            {

                TblBookingDAO bookingDAO = new TblBookingDAO(Global.CONNECTION_STRING);
                TblBooking booking = new TblBooking();

                if (Session[Global.SESSION_BOOK] == null)
                {
                    booking = new TblBooking();
                }
                else
                {
                    booking = (TblBooking)Session[Global.SESSION_BOOK];
                }

                TblCustomers userAccount = (TblCustomers)Session[Global.SESSION_LOGGED_USER];
                booking.Customer = userAccount;
                booking.CusID = userAccount.CusID;

                booking.DateActive = DateTime.Now;
                booking.DateBook = DateTime.Now;
                booking.Status = 1;
                booking.PaymentMethod = 1; // buy cash
                
                // order.Total = float.Parse(Session[Global.SESSION_TOTAL].ToString());

                booking.TotalPrice = Decimal.Parse(Session[Global.SESSION_TOTAL].ToString());

                List<TblBookingDetail> arrItems = (List<TblBookingDetail>)Session[Global.SESSION_CART];
                int id;

                
                bookingDAO.Insert(booking, arrItems, out id);

                //emailDAO.UpStatus(

                foreach (TblBookingDetail order in arrItems)
                {
                    emailDAO.UpStatus(order.IDEmail);                
                }

                Session[Global.SESSION_CART] = null;
                Session[Global.SESSION_TOTAL] = null;

                flag = true;

            }
            catch (Exception ex)
            {
                Session[Global.SESSION_ERROR] = ex;
                Response.Redirect(Global.ERROR_PAGE, true);
            }
            if (flag)
            {
                ScriptManager.RegisterStartupScript(btnPayment, btnPayment.GetType(), "alert", "alert('Order Successful!');", true);
                ScriptManager.RegisterStartupScript(btnPayment, btnPayment.GetType(), "ScriptLoginSuccess", "UpdatePayment();", true);
            }

            #endregion
        }

        // thanh toán paypal
        if (rd2.Checked == true)
        {
            if ((Session[Global.SESSION_TOTAL] == null) || (Session[Global.SESSION_CART] == null))
            {
                Response.Redirect("~/Default.aspx");
            }
            else
            {
                try
                {
                    string PaypalUsername = ConfigurationManager.AppSettings["PayPalUsername"].ToString();
                     int quantity = 0;
                     foreach (GridViewRow grd in grdShoppingCart.Rows)
                     {
                         quantity++;
                     }

                    double Totalamount = 0;
                    Totalamount = Convert.ToDouble(lblTotal.Text.Replace("$", ""));
                    string java = "if (window.parent.tb_remove != null) window.parent.tb_remove(); " +
                        "var newF =  window.parent.document.createElement('form'); " +
                        "newF.action = 'https://www.sandbox.paypal.com/cgi-bin/webscr'; newF.method = 'POST'; " +
                        "var newH = window.parent.document.createElement('input'); newH.name = 'return'; newH.type = 'hidden'; newH.value = 'http://pushmail.mprsc.com/Successful.aspx'; newF.appendChild(newH); " +
                        "var newH = window.parent.document.createElement('input'); newH.name = 'cmd'; newH.type = 'hidden'; newH.value = '_xclick'; newF.appendChild(newH); " +
                       "var newH = window.parent.document.createElement('input'); newH.name = 'business'; newH.type = 'hidden'; newH.value = '" + PaypalUsername + "'; newF.appendChild(newH); " +

                        "var newH = window.parent.document.createElement('input'); newH.name = 'item_name'; newH.type = 'hidden'; newH.value = 'Payment For Pushmail'; newF.appendChild(newH);" +
                        "var newH = window.parent.document.createElement('input'); newH.name = 'amount'; newH.type = 'hidden'; newH.value = '" + Totalamount + "'; newF.appendChild(newH);" +
                       "var newH = window.parent.document.createElement('input'); newH.name = 'quantity'; newH.type = 'hidden'; newH.value = '" + quantity + "'; newF.appendChild(newH);" +
                       "window.parent.document.getElementsByTagName('body')[0].appendChild(newF); " +
                        "newF.submit();";

                    ScriptManager.RegisterStartupScript(btnPayment, btnPayment.GetType(), "ScriptLoginSuccess", java, true);
                }
                catch (Exception ex)
                {
                    Session[Global.SESSION_ERROR] = ex;
                    Response.Redirect(Global.ERROR_PAGE, true);
                }
            }
        }
    }
}
